package com.gzhu.knowledgeAdmin.filter;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.gzhu.knowledgeAdmin.common.result.ErrorCode;
import com.gzhu.knowledgeAdmin.common.result.R;
import com.gzhu.knowledgeAdmin.common.utils.ResponseUtil;
import com.gzhu.knowledgeAdmin.entity.SecurityUser;
import com.gzhu.knowledgeAdmin.entity.User;
import com.gzhu.knowledgeAdmin.security.TokenManager;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 访问过滤器
 * </p>
 *
 * @author qy
 * @since 2019-11-08
 */
public class TokenAuthenticationFilter extends BasicAuthenticationFilter {
    private TokenManager tokenManager;
    private StringRedisTemplate stringRedisTemplate;

    // 定义允许直接访问的URL列表
    private static final List<String> ALLOWED_PATHS = Arrays.asList("/hmd/export");

    public TokenAuthenticationFilter(AuthenticationManager authManager, TokenManager tokenManager,StringRedisTemplate redisTemplate) {
        super(authManager);
        this.tokenManager = tokenManager;
        this.stringRedisTemplate = redisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        logger.info("================="+req.getRequestURI());
//        if(req.getRequestURI().indexOf("admin") == -1) {
//            chain.doFilter(req, res);
//            return;
//        }

        if (isPathAllowed(req.getRequestURI())) {
            chain.doFilter(req, res);
            return;
        }

        UsernamePasswordAuthenticationToken authentication ;
        try {
            authentication = getAuthentication(req);
        } catch (Exception e) {
            ResponseUtil.out(res, R.error(ErrorCode.TOKEN_INVALID));
            return;
        }

        if (authentication != null) {
            SecurityContextHolder.getContext().setAuthentication(authentication);
        } else {
            ResponseUtil.out(res, R.error(ErrorCode.TOKEN_INVALID));
            return;
        }
        chain.doFilter(req, res);
    }


    // 检查路径是否允许直接访问
    private boolean isPathAllowed(String requestURI) {
        for (String allowedPath : ALLOWED_PATHS) {
            if (requestURI.startsWith(allowedPath)) {
                return true;
            }
        }
        return false;
    }



    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        // token置于header里
        String token = request.getHeader("token");
        if (token != null && !"".equals(token.trim())) {
            String userName = tokenManager.getUserFromToken(token);

            // 验证出错
            if(StringUtils.isEmpty(userName)){
                return null;
            }

            String permissionValueListJson = stringRedisTemplate.opsForValue().get(userName);
            List<String> permissionValueList = JSON.parseObject(permissionValueListJson,new TypeReference<List<String>>(){});
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            for(String permissionValue : permissionValueList) {
                if(StringUtils.isEmpty(permissionValue)) continue;
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permissionValue);
                authorities.add(authority);
            }

            // 封装一个securityUser
            SecurityUser securityUser = new SecurityUser();
            securityUser.setPermissionValueList(permissionValueList);
            User user = getUser(userName);
            securityUser.setCurrentUserInfo(user);

            if (!StringUtils.isEmpty(userName)) {
                // 不再是保存userName，而是保存完整的用户信息
                return new UsernamePasswordAuthenticationToken(securityUser, token, authorities);
//                return new UsernamePasswordAuthenticationToken(userName, token, authorities);
            }
            return null;
        }
        return null;
    }

    private User getUser(String userName) {

        String userInfoJson = stringRedisTemplate.opsForValue().get("userInfo_" + userName);

        return JSON.parseObject(userInfoJson, new TypeReference<User>() {
        });

    }
}